from jmcomic import JmOptionPlugin
from jmcomic.jm_option import *
import os.path
import gc  # 引入垃圾回收机制

class MyImg2PdfPlugin(JmOptionPlugin):
    # 指定你的插件的key
    plugin_key = 'myimg2pdf'

    # 实现invoke方法
    def invoke(self,
               photo: JmPhotoDetail = None,
               album: JmAlbumDetail = None,
               downloader=None,
               pdf_dir_name:str="pdf",#不带斜杠
               filename_rule='Pindex',
               delete_original_file=False,
               **kwargs,
               ):
        if photo is None and album is None:
            jm_log('wrong_usage', 'myimg2pdf必须运行在after_photo或after_album时')
            return  # 添加 return 语句

        try:
            import img2pdf
        except ImportError:
            self.warning_lib_not_install('img2pdf')
            return

        self.delete_original_file = delete_original_file
        
        pdf_dir = ""
        # 如果不是整本
        if album is None:
            #获取本子目录
            pdf_dir = self.option.dir_rule.decide_album_root_dir(photo.from_album) + pdf_dir_name + "/"
        elif album is not None:
            pdf_dir = self.option.dir_rule.decide_album_root_dir(album) + pdf_dir_name + "/all/"
        else:
            print("错误：缺少必要的 album 或 photo.from_album 信息")
            return
            

        # 处理生成的pdf文件的路径
        pdf_dir = self.ensure_make_pdf_dir(pdf_dir)
        
        # 处理pdf文件名
        filename = DirRule.apply_rule_directly(album, photo, filename_rule)

        # pdf路径
        pdf_filepath = os.path.join(pdf_dir, f'{filename}.pdf')

        # 调用 img2pdf 把 photo_dir 下的所有图片转为pdf
        img_path_ls, img_dir_ls = self.write_img_2_pdf(pdf_filepath, album, photo)
        self.log(f'Convert Successfully: JM{album or photo} → {pdf_filepath}')

        # 执行删除
        img_path_ls += img_dir_ls
        self.execute_deletion(img_path_ls)

    def write_img_2_pdf(self, pdf_filepath, album: JmAlbumDetail, photo: JmPhotoDetail):
        import img2pdf

        if album is None:
            img_dir_ls = [self.option.decide_image_save_dir(photo)]
        else:
            img_dir_ls = [self.option.decide_image_save_dir(photo) for photo in album]

        img_path_ls = []

        for img_dir in img_dir_ls:
            imgs = files_of_dir(img_dir)
            if not imgs:
                continue
            img_path_ls += imgs

        valid_img_paths = []
        invalid_img_paths = []
        total = len(img_path_ls)

        self.log(f'开始验证图片兼容性，共 {total} 张图片')
        for i, img_path in enumerate(img_path_ls, 1):
            try:
                # 尝试用img2pdf转换单个图片来验证其兼容性
                img2pdf.convert([img_path])
                valid_img_paths.append(img_path)
                if i % 5 == 0:  # 每5张图片显示一次进度
                    self.log(f'进度: {i}/{total} ({i/total*100:.1f}%)')
            except Exception as e:
                self.log(f'图片 {img_path} 不兼容img2pdf: {str(e)}')

        if not valid_img_paths:
            raise Exception('没有可用的图片可以转换为PDF')

        with open(pdf_filepath, 'wb') as f:
            f.write(img2pdf.convert(valid_img_paths))
        # 强制释放资源
        gc.collect()
        return valid_img_paths, img_dir_ls

    @staticmethod
    def ensure_make_pdf_dir(pdf_dir: str):
        pdf_dir = pdf_dir or os.getcwd()
        pdf_dir = fix_filepath(pdf_dir, True)
        mkdir_if_not_exists(pdf_dir)
        return pdf_dir

# 让plugin类生效
JmModuleConfig.register_plugin(MyImg2PdfPlugin)